package rpcsupport

import (
	"net/rpc"
	"net"
	"net/rpc/jsonrpc"
	"log"
)

func ServeRpc(host string, service interface{}) error  {
	//注册rpcdemo 为prc的对象
	rpc.Register(service)
	listener, err := net.Listen("tcp", host)
	if err != nil {
		return err
	}
	log.Printf("Listening on %s", host)
	for {
		//等待接受者
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("accetp error: %v", err)
			continue
		}

		//把接受的conn信息放入到jsonrpc里；阻塞
		go jsonrpc.ServeConn(conn)
	}

	return nil
}

func NewClient(host string) (*rpc.Client,error)  {
	conn, err := net.Dial("tcp", host)
	if err != nil {
		return nil,err
	}
	log.Printf("accessing on %s", host)
	return jsonrpc.NewClient(conn), nil
}
